import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'index.dart';
import '../../../common/models/index.dart';
import '../../../common/utils/index.dart';

class ShenbaoAssessmentPage extends GetView<ShenbaoAssessmentController> {
  const ShenbaoAssessmentPage({super.key});

  // 主视图
  Widget _buildView() {
    return Obx(() {
      // 显示加载状态（优化设计）
      if (controller.isLoading.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      const Color(0xFFFF6B6B).withValues(alpha: 0.1),
                      const Color(0xFFD84545).withValues(alpha: 0.05),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(30),
                ),
                child: const Center(
                  child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF6B6B)),
                    strokeWidth: 3,
                  ),
                ),
              ),
              const SizedBox(height: 20),
              const Text(
                '正在加载评审项目...',
                style: TextStyle(
                  fontSize: 14,
                  color: Color(0xFF666666),
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        );
      }

      // 显示错误状态（优化设计）
      if (controller.errorMessage.value.isNotEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 120,
                height: 120,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Colors.red.shade400.withValues(alpha: 0.1),
                      Colors.red.shade600.withValues(alpha: 0.05),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(60),
                ),
                child: Icon(
                  Icons.error_outline_rounded,
                  size: 64,
                  color: Colors.red.shade400,
                ),
              ),
              const SizedBox(height: 24),
              const Text(
                '加载失败',
                style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(height: 8),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 40),
                child: Text(
                  controller.errorMessage.value,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.red.shade400,
                    fontSize: 13,
                  ),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const SizedBox(height: 24),
              Container(
                height: 46,
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                  ),
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFFD84545).withValues(alpha: 0.3),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: ElevatedButton(
                  onPressed: controller.refreshProjectList,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    foregroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    elevation: 0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 24),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.refresh_rounded, size: 20),
                        SizedBox(width: 6),
                        Text(
                          '重试',
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }

      // 显示空数据状态（优化设计）
      if (controller.projectList.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 120,
                height: 120,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      const Color(0xFFFF6B6B).withValues(alpha: 0.1),
                      const Color(0xFFD84545).withValues(alpha: 0.05),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(60),
                ),
                child: const Icon(
                  Icons.inbox_outlined,
                  size: 64,
                  color: Color(0xFFFF6B6B),
                ),
              ),
              const SizedBox(height: 24),
              const Text(
                '暂无评审项目',
                style: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                '下拉刷新试试',
                style: TextStyle(
                  color: Color(0xFF999999),
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 24),
              Container(
                height: 46,
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                  ),
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: const Color(0xFFD84545).withValues(alpha: 0.3),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: ElevatedButton(
                  onPressed: controller.refreshProjectList,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    foregroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    elevation: 0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 24),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.refresh_rounded, size: 20),
                        SizedBox(width: 6),
                        Text(
                          '刷新',
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }

      // 显示项目列表（现代化设计）
      return RefreshIndicator(
        onRefresh: controller.refreshProjectList,
        color: const Color(0xFFFF6B6B),  // 设计规范：主色
        child: ListView.builder(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),  // 设计规范：页面边距
          itemCount: controller.projectList.length,
          itemBuilder: (context, index) {
            final project = controller.projectList[index];
            return _buildProjectCard(project);
          },
        ),
      );
    });
  }

  // 构建项目卡片（现代化设计）
  Widget _buildProjectCard(project) {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 6, 10, 6),  // 设计规范：外边距
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),         // 设计规范：圆角12px
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.04),      // 设计规范：Level 1 阴影
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(10.0),        // 设计规范：内边距
        child: Material(
          color: Colors.transparent,
          child: Padding(
            padding: EdgeInsets.zero,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 项目标题（带渐变图标）
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(5),
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(  // 设计规范：主色渐变
                          colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                        ),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Icon(
                        Icons.assignment_outlined,
                        color: Colors.white,
                        size: 14,
                      ),
                    ),
                    const SizedBox(width: 6),
                    Expanded(
                      child: Text(
                        project.projectName ?? '未命名项目',
                        style: const TextStyle(
                          fontSize: 15,                  // 设计规范：重要信息字号
                          fontWeight: FontWeight.w600,
                          color: Color(0xFF333333),      // 设计规范：文字主色
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                
                // 项目信息区域（带背景）
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: const Color(0xFFF8F9FA),     // 设计规范：内容区背景
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Column(
                    children: [
                      // 项目编号
                      if (project.projectNo != null && project.projectNo != 'null')
                        _buildInfoRow(
                          icon: Icons.tag_outlined,
                          iconColor: const Color(0xFF4FC3F7),
                          label: '编号',
                          value: project.projectNo!,
                        ),
                      
                      if (project.projectNo != null && 
                          (project.declareDepartment != null || project.budgetAmount != null))
                        const SizedBox(height: 6),
                      
                      // 申报部门
                      if (project.declareDepartment != null && project.declareDepartment != 'null')
                        _buildInfoRow(
                          icon: Icons.business_outlined,
                          iconColor: const Color(0xFF9C27B0),
                          label: '部门',
                          value: project.declareDepartment!,
                        ),
                      
                      if (project.declareDepartment != null && project.budgetAmount != null)
                        const SizedBox(height: 6),
                      
                      // 预算金额
                      if (project.budgetAmount != null && project.budgetAmount.toString() != 'null')
                        _buildInfoRow(
                          icon: Icons.monetization_on_outlined,
                          iconColor: const Color(0xFF66BB6A),
                          label: '预算',
                          value: '${project.budgetAmount}万元',
                        ),
                    ],
                  ),
                ),
                
                const SizedBox(height: 10),
                
                // 状态和操作按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 状态标签
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            _getStatusColor(project.status),
                            _getStatusColor(project.status).withValues(alpha: 0.8),
                          ],
                        ),
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: [
                          BoxShadow(
                            color: _getStatusColor(project.status).withValues(alpha: 0.3),
                            blurRadius: 4,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Text(
                        _getStatusText(project.status),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    // 开始评审按钮
                    Builder(
                      builder: (context) => InkWell(
                        onTap: () async {
                          await controller.onProjectTap(project);
                          
                          // 根据投票状态显示对应的弹出框
                          if (controller.voteSheetType.value == 'election') {
                            _showVoteElectionSheet(context);
                          } else if (controller.voteSheetType.value == 'progress') {
                            _showVoteProgressSheet(context);
                          } else if (controller.voteSheetType.value == 'result') {
                            _showVoteResultSheet(context);
                          }
                        },
                      borderRadius: BorderRadius.circular(12),
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(
                            color: const Color(0xFFFF6B6B),
                            width: 1.5,
                          ),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              '开始评审',
                              style: TextStyle(
                                color: const Color(0xFFFF6B6B),
                                fontSize: 13,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            const SizedBox(width: 4),
                            Icon(
                              Icons.gavel,
                              size: 12,
                              color: const Color(0xFFFF6B6B),
                            ),
                          ],
                        ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建信息行
  Widget _buildInfoRow({
    required IconData icon,
    required Color iconColor,
    required String label,
    required String value,
  }) {
    return Row(
      children: [
        Container(
          width: 24,
          height: 24,
          padding: const EdgeInsets.all(5),
          decoration: BoxDecoration(
            color: iconColor.withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(6),
          ),
          child: Icon(
            icon,
            color: iconColor,
            size: 14,
          ),
        ),
        const SizedBox(width: 6),
        Expanded(
          child: RichText(
            text: TextSpan(
              children: [
                TextSpan(
                  text: '$label：',
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF999999),      // 设计规范：文字辅助色
                    fontWeight: FontWeight.w500,
                    fontFamily: 'PingFang SC',
                  ),
                ),
                TextSpan(
                  text: value,
                  style: const TextStyle(
                    fontSize: 13,
                    color: Color(0xFF333333),      // 设计规范：文字主色
                    fontWeight: FontWeight.w600,
                    fontFamily: 'PingFang SC',
                  ),
                ),
              ],
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }

  // 获取状态颜色（使用ProjectModel的状态管理）
  Color _getStatusColor(int? status) {
    return ProjectModel.getStatusColorByValue(status);
  }

  // 获取状态文本（使用ProjectModel的状态管理）
  String _getStatusText(int? status) {
    return ProjectModel.getStatusTextByValue(status);
  }

  /// 显示投票选举弹出框
  void _showVoteElectionSheet(BuildContext context) {
    Get.bottomSheet(
      _VoteElectionSheet(controller: controller),
      isScrollControlled: true,
      isDismissible: true,
      enableDrag: true,
    );
  }
  
  /// 显示投票进度弹出框
  void _showVoteProgressSheet(BuildContext context) {
    Get.bottomSheet(
      _VoteProgressSheet(controller: controller),
      isScrollControlled: true,
      isDismissible: true,
      enableDrag: true,
    );
  }
  
  /// 显示选举结果弹出框
  void _showVoteResultSheet(BuildContext context) {
    Get.bottomSheet(
      _VoteResultSheet(controller: controller),
      isScrollControlled: true,
      isDismissible: false,
      enableDrag: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    // 设置状态栏样式
    SystemUIUtils.setTransparentStatusBarDark();
    
    // 从路由参数获取动态标题
    final arguments = Get.arguments as Map<String, dynamic>? ?? {};
    final pageTitle = arguments['pageTitle'] as String? ?? '项目申报评审';
    
    return GetBuilder<ShenbaoAssessmentController>(
      init: ShenbaoAssessmentController(),
      id: "shenbao_assessment",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF8F9FA),  // 设计规范：页面背景色
          appBar: AppBar(
            backgroundColor: Colors.white,
            foregroundColor: const Color(0xFF333333),
            elevation: 0,
            leading: IconButton(
              onPressed: () => Navigator.pop(context),
              icon: const Icon(Icons.arrow_back_ios),
            ),
            title: Text(
              pageTitle,
              style: const TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.bold,
              ),
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.refresh_rounded),
                onPressed: controller.refreshProjectList,
                tooltip: '刷新',
              ),
            ],
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}

/// 🗳️ 投票选举弹出框组件
class _VoteElectionSheet extends StatelessWidget {
  final ShenbaoAssessmentController controller;
  
  const _VoteElectionSheet({required this.controller});

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.75,
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildHeader(),
          Flexible(
            child: SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildDescription(),
                  const SizedBox(height: 20),
                  _buildExpertList(),
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ),
          _buildBottomButton(),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.only(top: 8, bottom: 12),
      child: Column(
        children: [
          Container(
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey.shade300,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(height: 12),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                Icon(Icons.how_to_vote_outlined, color: Colors.blue.shade600, size: 24),
                const SizedBox(width: 8),
                const Expanded(
                  child: Text(
                    '评审组长选举',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.close, size: 24, color: Colors.grey.shade600),
                  onPressed: () => Get.back(),
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDescription() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.blue.shade200),
      ),
      child: Row(
        children: [
          Icon(Icons.info_outline, color: Colors.blue.shade600, size: 20),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              '请投票选举本项目的评审组长，每位专家只能投票一次',
              style: TextStyle(
                fontSize: 14,
                color: Colors.blue.shade900,
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildExpertList() {
    return Obx(() {
      final experts = controller.projectExperts;
      
      if (experts.isEmpty) {
        return Center(
          child: Padding(
            padding: const EdgeInsets.all(32),
            child: Column(
              children: [
                Icon(Icons.people_outline, size: 48, color: Colors.grey.shade400),
                const SizedBox(height: 12),
                Text(
                  '暂无专家信息',
                  style: TextStyle(color: Colors.grey.shade600, fontSize: 14),
                ),
              ],
            ),
          ),
        );
      }
      
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '请选择要投票的专家：',
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w600,
              color: Colors.grey.shade800,
            ),
          ),
          const SizedBox(height: 12),
          ...experts.map((expert) => _buildExpertItem(expert)),
        ],
      );
    });
  }

  Widget _buildExpertItem(ProjectExpert expert) {
    return Obx(() {
      final isSelected = controller.selectedExpertId.value == expert.expertId;
      final isSelf = expert.expertId == controller.currentExpertId;
      
      return GestureDetector(
        onTap: () {
          controller.selectedExpertId.value = expert.expertId ?? 0;
        },
        child: Container(
          margin: const EdgeInsets.only(bottom: 12),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: isSelected ? Colors.blue.shade50 : Colors.white,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: isSelected ? Colors.blue.shade400 : Colors.grey.shade300,
              width: isSelected ? 2 : 1,
            ),
          ),
          child: Row(
            children: [
              Icon(
                isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
                color: isSelected ? Colors.blue.shade600 : Colors.grey.shade400,
                size: 24,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text(
                          expert.expertName ?? '未知专家',
                          style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.w600,
                            color: Colors.black87,
                          ),
                        ),
                        if (isSelf) ...[
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              color: Colors.blue.shade100,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              '我',
                              style: TextStyle(
                                fontSize: 11,
                                color: Colors.blue.shade700,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                    if (expert.corpName != null && expert.corpName!.isNotEmpty) ...[
                      const SizedBox(height: 4),
                      Text(
                        expert.corpName!,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ],
          ),
        ),
      );
    });
  }

  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade200,
            offset: const Offset(0, -2),
            blurRadius: 8,
          ),
        ],
      ),
      child: SafeArea(
        child: Obx(() {
          final hasSelected = controller.selectedExpertId.value > 0;
          
          return SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: hasSelected ? () async {
                await controller.submitVote();
                
                await Future.delayed(const Duration(milliseconds: 600));
                if (controller.voteSheetType.value == 'progress') {
                  Get.bottomSheet(
                    _VoteProgressSheet(controller: controller),
                    isScrollControlled: true,
                    isDismissible: true,
                    enableDrag: true,
                  );
                } else if (controller.voteSheetType.value == 'result') {
                  Get.bottomSheet(
                    _VoteResultSheet(controller: controller),
                    isScrollControlled: true,
                    isDismissible: false,
                    enableDrag: false,
                  );
                }
              } : null,
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 14),
                backgroundColor: Colors.blue.shade600,
                foregroundColor: Colors.white,
                disabledBackgroundColor: Colors.grey.shade300,
                disabledForegroundColor: Colors.grey.shade600,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: const Text(
                '提交投票',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
              ),
            ),
          );
        }),
      ),
    );
  }
}

/// 📊 投票进度弹出框组件
class _VoteProgressSheet extends StatelessWidget {
  final ShenbaoAssessmentController controller;
  
  const _VoteProgressSheet({required this.controller});

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.5,
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildHeader(),
          Flexible(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  _buildProgressIcon(),
                  const SizedBox(height: 24),
                  _buildProgressInfo(),
                  const SizedBox(height: 24),
                  _buildRefreshButton(),
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.only(top: 8, bottom: 12),
      child: Column(
        children: [
          Container(
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey.shade300,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(height: 12),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                Icon(Icons.poll_outlined, color: Colors.orange.shade600, size: 24),
                const SizedBox(width: 8),
                const Expanded(
                  child: Text(
                    '投票进行中',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                ),
                IconButton(
                  icon: Icon(Icons.close, size: 24, color: Colors.grey.shade600),
                  onPressed: () => Get.back(),
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProgressIcon() {
    return Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        color: Colors.orange.shade50,
        shape: BoxShape.circle,
      ),
      child: Icon(
        Icons.how_to_vote,
        size: 50,
        color: Colors.orange.shade600,
      ),
    );
  }

  Widget _buildProgressInfo() {
    return Obx(() {
      final expertNum = controller.expertNum.value;
      final votedNum = controller.votedNum.value;
      final progress = expertNum > 0 ? votedNum / expertNum : 0.0;
      
      return Column(
        children: [
          Text(
            '您已完成投票',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: Colors.grey.shade800,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '请等待其他专家完成投票',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey.shade600,
            ),
          ),
          const SizedBox(height: 24),
          
          Container(
            width: double.infinity,
            height: 8,
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: BorderRadius.circular(4),
            ),
            child: FractionallySizedBox(
              alignment: Alignment.centerLeft,
              widthFactor: progress,
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Colors.orange.shade400, Colors.orange.shade600],
                  ),
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
            ),
          ),
          const SizedBox(height: 12),
          
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '$votedNum',
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Colors.orange.shade600,
                ),
              ),
              Text(
                ' / $expertNum',
                style: TextStyle(
                  fontSize: 18,
                  color: Colors.grey.shade600,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                '专家已投票',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey.shade600,
                ),
              ),
            ],
          ),
        ],
      );
    });
  }

  Widget _buildRefreshButton() {
    return OutlinedButton.icon(
      onPressed: () async {
        await controller.refreshVoteStatus();
        
        if (controller.votedNum.value >= controller.expertNum.value && 
            controller.expertNum.value > 0) {
          Get.back();
          
          await Future.delayed(const Duration(milliseconds: 300));
          await controller.checkVoteStatusAndShow();
          
          if (controller.voteSheetType.value == 'result') {
            Get.bottomSheet(
              _VoteResultSheet(controller: controller),
              isScrollControlled: true,
              isDismissible: false,
              enableDrag: false,
            );
          }
        }
      },
      icon: const Icon(Icons.refresh, size: 18),
      label: const Text('刷新投票状态'),
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        foregroundColor: Colors.orange.shade600,
        side: BorderSide(color: Colors.orange.shade600),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
    );
  }
}

/// 🎉 选举结果弹出框组件
class _VoteResultSheet extends StatelessWidget {
  final ShenbaoAssessmentController controller;
  
  const _VoteResultSheet({required this.controller});

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.6,
      ),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildHeader(),
          Flexible(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  _buildCompletionIcon(),
                  const SizedBox(height: 24),
                  _buildElectionResult(),
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ),
          _buildBottomButton(),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.only(top: 8, bottom: 12),
      child: Column(
        children: [
          Container(
            width: 40,
            height: 4,
            decoration: BoxDecoration(
              color: Colors.grey.shade300,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(height: 12),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                Icon(Icons.emoji_events, color: Colors.green.shade600, size: 24),
                const SizedBox(width: 8),
                const Expanded(
                  child: Text(
                    '选举结果',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCompletionIcon() {
    return Container(
      width: 100,
      height: 100,
      decoration: BoxDecoration(
        color: Colors.green.shade50,
        shape: BoxShape.circle,
      ),
      child: Icon(
        Icons.check_circle,
        size: 50,
        color: Colors.green.shade600,
      ),
    );
  }

  Widget _buildElectionResult() {
    return Obx(() {
      final electedLeaderId = controller.electedLeaderId.value;
      final experts = controller.projectExperts;
      final electedLeader = experts.firstWhere(
        (e) => e.expertId == electedLeaderId,
        orElse: () => ProjectExpert(expertName: '未知专家'),
      );
      final isCurrentUserLeader = (electedLeaderId == controller.currentExpertId);
      
      return Column(
        children: [
          Text(
            '投票已完成',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.grey.shade800,
            ),
          ),
          const SizedBox(height: 24),
          
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Colors.green.shade50, Colors.green.shade100],
              ),
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Colors.green.shade300, width: 2),
            ),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.emoji_events, color: Colors.amber.shade700, size: 28),
                    const SizedBox(width: 8),
                    Text(
                      '评审组长',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: Colors.green.shade800,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                Text(
                  electedLeader.expertName ?? '未知专家',
                  style: TextStyle(
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                    color: Colors.green.shade900,
                  ),
                ),
                if (electedLeader.corpName != null && electedLeader.corpName!.isNotEmpty) ...[
                  const SizedBox(height: 6),
                  Text(
                    electedLeader.corpName!,
                    style: TextStyle(
                      fontSize: 13,
                      color: Colors.green.shade700,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
                if (isCurrentUserLeader) ...[
                  const SizedBox(height: 12),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.amber.shade100,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: Colors.amber.shade300),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.star, color: Colors.amber.shade700, size: 16),
                        const SizedBox(width: 4),
                        Text(
                          '您是组长',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                            color: Colors.amber.shade900,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            ),
          ),
          
          const SizedBox(height: 20),
          
          Obx(() {
            final expertNum = controller.expertNum.value;
            final votedNum = controller.votedNum.value;
            
            return Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildStatItem('参与专家', '$expertNum', Icons.people),
                  Container(
                    width: 1,
                    height: 40,
                    color: Colors.grey.shade300,
                  ),
                  _buildStatItem('已投票', '$votedNum', Icons.how_to_vote),
                ],
              ),
            );
          }),
        ],
      );
    });
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(icon, color: Colors.blue.shade600, size: 20),
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.blue.shade700,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey.shade600,
          ),
        ),
      ],
    );
  }

  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade200,
            offset: const Offset(0, -2),
            blurRadius: 8,
          ),
        ],
      ),
      child: SafeArea(
        child: SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: controller.enterReviewDetail,
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 14),
              backgroundColor: Colors.green.shade600,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: const Text(
              '进入项目评审',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
            ),
          ),
        ),
      ),
    );
  }
}
